package chalmers.game.subterranean.model;

import chalmers.game.subterranean.event.Bus;
import chalmers.game.subterranean.event.events.minors.SpawnMinorEvent;
import chalmers.game.subterranean.model.physics.MovableBody;
import chalmers.game.subterranean.model.player.IPlayer;
import chalmers.game.subterranean.model.player.PlayerFactory;
import chalmers.game.subterranean.model.world.GameWorld;
import chalmers.game.subterranean.model.world.IWorld;
import chalmers.game.subterranean.util.Position;
import chalmers.game.subterranean.util.options.Speeds;
import chalmers.game.subterranean.util.options.Variables;

import java.util.ArrayList;
import java.util.List;

public class Subterranean implements ISubterranean {

  public final IWorld gameWorld;
  public final IPlayer player;
  private final List<MovableBody> minors = new ArrayList<>();
  private final MinorsHandler minorsHandler;
  private boolean spawn = true;
  private final int numberOfMinors = 1;

  public Subterranean() {
    gameWorld = new GameWorld();
    player = PlayerFactory.createPlayer(gameWorld);
    minorsHandler = new MinorsHandler();
  }

  /**
   * This is needed if the control is going to call methods directly in player
   */
  @Override
  public void start() {
    gameWorld.start();
    Clock.start(Variables.CLOCK_TIME_INTERVAL, this);
  }

  @Override
  public IPlayer getPlayer() {
    return this.player;
  }

  @Override
  public void progressTime() {
    player.movePlayer();
    spawn();
    for (MovableBody minor : minors) {
      minorsHandler.moveMinor(minor);
    }
  }

  /**
   * Spawn a minor if needed.
   */
  private void spawn() {
    if (spawn && gameWorld != null) {
      MovableBody minor;
      spawn = false;
      for (int i = 0; i < 15; i += 5) {
        minor = new MovableBody();
        minor.setXVelocity(Speeds.RUNSPEED);
        minor.setWorld(gameWorld);
        minor.setPosition(new Position(0, i, 5));
        minors.add(minor);
        Bus.INSTANCE.post(new SpawnMinorEvent(minor.hashCode(), minor.getExactPosition()));
      }
    }
  }
}
